# -*- coding: utf-8 -*-
import pygame
import world
import grid
import os, sys
import map
import marker, selector
           
class Game(object):
    def __init__(self):
        pygame.init()
        
        self.system = world.System()
        
        self.system.set_screen (800, 600)
    
        self.system.register_font ("deja", 8, os.path.join("res","font","DejaVuSans.ttf"))
        self.system.register_font ("deja", 14, os.path.join("res","font","DejaVuSans.ttf"))
        self.system.register_font ("deja", 18, os.path.join("res","font","DejaVuSans.ttf"))
         
        #grid_origin, tile_width, tile_height, tile_pixel_size):
        self.grid = grid.Pathfinding_Grid ((0,0), 100, 100, (20,20))
        self.grid.enable_zbuffer ()
              
        self.world = world.World()
        self.world.grid = self.grid
        creator = world.creator.World_creator(self.world)
        creator.create_world() 
        
        self.world.grid = self.grid
        
        # Or maybe register renderer in system object
        self.renderer = world.render.WorldRenderer (self.world, self.system)
        
        self.DEBUG = True
        self.running = True
        
        ## load from file
        #self.loadMap(os.path.join ("res", "map.save"))
        
        self.timer = pygame.time.Clock()
        self.scrollKey = None
        #self.objcount = 0
        self.linecount = 0
        
        # Initialize GUI
        #self.info = cScreenInfo (self.grid, self.SCREEN)
        self.main()
        
    # TODO: Split events into subsystems: what is ui related, what is releated to system (exit)
    # and what else ?
    def keyboard_events (self, event):
        if event.type == pygame.QUIT: 
            self.running = False
        if event.type == pygame.KEYDOWN:            
            if event.key == pygame.K_RIGHT \
            or event.key == pygame.K_LEFT \
            or event.key == pygame.K_UP \
            or event.key == pygame.K_DOWN:
                self.scrollKey = event.key
        if event.type == pygame.KEYUP:
            if event.key == pygame.K_RIGHT \
            or event.key == pygame.K_LEFT \
            or event.key == pygame.K_UP \
            or event.key == pygame.K_DOWN:
                self.scrollKey = None 
            if event.key == pygame.K_ESCAPE:
                self.running = False
            if event.key == pygame.K_s:
                self.saveMap("map.save")
            # debug map
            if event.key == pygame.K_m:
                if self.world.has_render_layer ("map"):
                    self.world.del_render_layer ("map")
                else:
                    # create a map layer for overlay
                    m = map.TileMap (self.world)
                    surface = m.create_map_surface_from_grid ()
                    self.world.set_render_layer ("map", surface, None)
            # mini map
            if event.key == pygame.K_n:
                if self.world.has_render_layer ("minimap"):
                    self.world.del_render_layer ("minimap")
                else:
                    m = map.TileMap (self.world)
                    surface = m.create_map_surface_from_grid ()
                    surface2 = pygame.transform.scale (surface, (200,200))
                    self.world.set_render_layer ("minimap", surface2, None)

    # TODO: Split events into subsystems: what is ui related, what is releated to system (exit)
    # and what else ?
    def mouse_events (self, event):
       if event.type == pygame.MOUSEBUTTONUP:
            if event.button == 1:
                sel_rect = marker.getMarkRect()
            
                for item in selector.SelectionRegistry.getAll():
                    r = pygame.Rect (self.grid.g2s(item.tPosPi), item.rRect.size)
                    if r.colliderect(sel_rect):
                        item.setMarked()
                        selector.activeSelector.addItem(item)
                
                tile = self.grid.get_tile_at_pixelpos(self.grid.s2g(event.pos))
                if tile != None:
                    print self.grid.get_objs_for_tag (tile)
        
    # E V E N T 
    def main_handle_events (self):        
        for event in pygame.event.get():
            marker.handleMarkingEvents (event)
            selector.handleSelectionEvents (event)
            self.keyboard_events(event)
            self.mouse_events(event)
            
            
        # Action (scroll) -> this is not part of event handling, but of UI update!
        # this interpretates a already handled event inside the event loop
        if self.scrollKey == pygame.K_UP: self.grid.scrollUp (5)
        if self.scrollKey == pygame.K_DOWN: self.grid.scrollDown (5, self.system.scr_h)
        if self.scrollKey == pygame.K_LEFT: self.grid.scrollLeft (5)
        if self.scrollKey == pygame.K_RIGHT: self.grid.scrollRight (5, self.system.scr_w)            
        
#        mx, my = pygame.mouse.get_pos()
#        if self.info.isVillageInfoShown():
#            if mx <= 600:
#                self.info.hideVillageInfo() 
#        else:
#            if mx >= 770:
#                if my > 10 and my < 210:
#                    self.info.showVillageInfo()
                      
        
    # M A I N L O O P
    #TODO: übergabe der temp. Variables -- über self ?? wie am besten
    def main(self):
        fps_max = 0
        fps = 0
        fps_avg = [i for i in xrange(0,100)]
        #fps_avg_c = fps_avg_val = 0
        
        scrollKey = None
        while self.running:            
            self.main_handle_events()
            #self.main_calculate_ai()
            #self.renderer.main_render_pipeline (fps, fps_max, fps_avg)
            self.renderer.render_world ()
        

  
 
if __name__ == "__main__":
    pass
    
#    
#    import traceback,sys
#
#    game = Game()
#    if "profile" in sys.argv:
#        import hotshot
#        import hotshot.stats
#        import tempfile
#        import os
# 
#       
#        
#        profile_data_fname = tempfile.mktemp("prf")
#        try:
#            prof = hotshot.Profile(profile_data_fname)
#            prof.run('game.main()')
#            del prof
#            s = hotshot.stats.load(profile_data_fname)
#            s.strip_dirs()
#            print "cumulative\n\n"
#            s.sort_stats('cumulative').print_stats()
#            print "By time.\n\n"
#            s.sort_stats('time').print_stats()
#            del s
#        finally:
#            # clean up the temporary file name.
#            pygame.quit()
#            try:
#                os.remove(profile_data_fname)
#            except:
#                # may have trouble deleting ;)
#                pass
#    else:
#        try:
#            game.main()
#            pygame.quit()
#        except:
#            traceback.print_exc(sys.stderr)

